package com.medicinezp.webpcapi;

import com.medicinezp.baseconfig.domain.*;
import com.medicinezp.baseconfig.mapper.BaseUserJobApplyMapper;
import com.medicinezp.baseconfig.service.*;
import com.medicinezp.common.annotation.Log;
import com.medicinezp.common.config.AliConfig;
import com.medicinezp.common.config.MedicinezpConfig;
import com.medicinezp.common.core.controller.BaseController;
import com.medicinezp.common.core.domain.AjaxResult;
import com.medicinezp.common.core.domain.entity.SysUser;
import com.medicinezp.common.core.domain.model.LoginUser;
import com.medicinezp.common.core.page.TableDataInfo;
import com.medicinezp.common.enums.BusinessType;
import com.medicinezp.common.utils.DateUtils;
import com.medicinezp.common.utils.DictUtils;
import com.medicinezp.common.utils.SecurityUtils;
import com.medicinezp.common.utils.StringUtils;
import com.medicinezp.common.utils.file.FileUploadUtils;
import com.medicinezp.system.service.ISysUserService;
import com.medicinezp.webpcapi.vo.UserVo;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 不需要授权接口
 *
 * @author waoqi
 * @date 2021-08-18
 */
@RestController
@RequestMapping("/api/service")
public class serviceController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger(serviceController.class);

    @Autowired
    private ISysUserService sysUserService;


    @Autowired
    private IBaseUserResumeService baseResumeService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IBaseUserInviteApplyService baseUserInviteApplyService;
    @Autowired
    private IBaseJobsService baseJobsService;

    @Autowired
    private IBaseUserJobApplyLogsService baseUserJobApplyLogsService;

    @Autowired
    private IBaseUserJobApplyService baseUserJobApplyService;

    @Autowired
    private IBaseJobCategoryService baseJobCategoryService;

    @Autowired
    private IBaseJobTypeService baseJobTypeService;

    @Autowired
    private IBaseCompanyAddressService companyAddressService;

    @Autowired
    private IBaseCompanyService baseCompanyService;

    @Autowired
    private IBaseCompanyPhotoService baseCompanyPhotoService;

    @Autowired
    private IBaseCompanyAccountRealService baseCompanyAccountRealService;

    @Autowired
    private IBaseRegionProvinceService baseRegionProvinceService;

    @Autowired
    private IBaseSearchHistoryService baseSearchHistoryService;

    @Autowired
    private IBaseJobLogsService baseJobLogsService;

    @GetMapping("/getCompanyJobList")
    public AjaxResult getCompanyJobList(BaseJobs baseJobs)
    {
        SysUser currentUser=SecurityUtils.getLoginUser().getUser();
        if(currentUser.getCurrentCompanyid()==null){
            return AjaxResult.success(new ArrayList<>());
        }
        baseJobs.setCompanyId(currentUser.getCurrentCompanyid());
        baseJobs.setStatus("02");
        List<BaseJobs> list = baseJobsService.selectMyCompanyJobsList(baseJobs);
        return AjaxResult.success(list);
    }

    @GetMapping("/getCompanyJobData")
    public TableDataInfo getCompanyJobData(BaseJobs baseJobs)
    {
        SysUser currentUser=SecurityUtils.getLoginUser().getUser();
        if(currentUser.getCurrentCompanyid()==null){
            return getDataTable(new ArrayList<>());
        }
        if(StringUtils.isNotEmpty(baseJobs.getStatus())){
            String statusStr="'"+baseJobs.getStatus().replaceAll(",","','")+"'";
            baseJobs.setStatus(statusStr);
        }
        baseJobs.setCompanyId(currentUser.getCurrentCompanyid());
        startPage();
        List<BaseJobs> list = baseJobsService.selectBaseJobsList(baseJobs);
        List<BaseCompanyAddress> addrList=companyAddressService.selectBaseCompanyAddressList(new BaseCompanyAddress());
        list.stream().forEach(job->{
            BaseCompanyAddress address= addrList.stream().filter(addr->addr.getId().intValue()==job.getAddrId().intValue()).findFirst().orElse(null);
            if(address!=null) {
                job.setCompanyAddress(address);
            }
        });
        return getDataTable(list);
    }

    @GetMapping("/getCompanyJobDetail/{id}")
    public AjaxResult getCompanyJobDetail(@PathVariable("id") Long id)
    {
        BaseJobs job = baseJobsService.selectBaseJobsById(id);
        job.setCompanyAddress(companyAddressService.selectBaseCompanyAddressById(job.getAddrId()));
        return AjaxResult.success(job);
    }

    /**
     * 关闭岗位
     * @param id
     * @return
     */
    @GetMapping("/closeCompanyJobData/{id}")
    public AjaxResult closeCompanyJobData(@PathVariable("id") Long id)
    {
        BaseJobs job = baseJobsService.selectBaseJobsById(id);
        if(job==null){
            return AjaxResult.error("岗位不存在");
        }
        job.setStatus("00");
        job.setUpdateBy(SecurityUtils.getUsername());
        job.setUpdateTime(DateUtils.getNowDate());
        int result= baseJobsService.updateBaseJobsInfo(job);
        if(result>0){
            BaseJobLogs log=new BaseJobLogs();
            log.setJobId(job.getId());
            log.setContent("关闭职位");
            log.setCreateTime(DateUtils.getNowDate());
            log.setCreateBy(SecurityUtils.getUsername());
            log.setRemark("");
            log.setCreateAvatar(SecurityUtils.getLoginUser().getUser().getAvatar());
            baseJobLogsService.insertBaseJobLogs(log);
        }
        return toAjax(result);
    }

    @GetMapping("/getCompanyJobTypeCount")
    public AjaxResult getCompanyJobTypeCount(BaseJobs baseJobs)
    {
        SysUser currentUser=SecurityUtils.getLoginUser().getUser();
        if(currentUser.getCurrentCompanyid()==null){
            return AjaxResult.success(new ArrayList<>());
        }
        baseJobs.setCompanyId(currentUser.getCurrentCompanyid());
        List<BaseJobs> list = baseJobsService.selectBaseJobsCountList(baseJobs);
        return AjaxResult.success(list);
    }
    /**
     * 推荐人才
     * @param user
     * @return
     */
    @GetMapping("/getReferrerUserslist")
    public TableDataInfo getReferrerUserslist(UserVo user)
    {
        startPage();
        List<SysUser> list = userService.selectReferrerUserList(user);
        list.stream().forEach(userinfo->{
            BaseUserInviteApply apply=new BaseUserInviteApply();
            apply.setUserId(userinfo.getUserId());
            apply.setJobId(user.getJobId());
            List<BaseUserInviteApply>  inviteList= baseUserInviteApplyService.selectBaseUserInviteApplyList(apply);
            userinfo.setInviteFlag(false);
            if(inviteList.size()>0){
                userinfo.setInviteFlag(true);
            }
            BaseUserResume resume= baseResumeService.getUserResume(userinfo.getUserId());
            if(userinfo.getBirthDate()!=null){
                int age= DateUtils.differentDaysByMillisecond(userinfo.getBirthDate(),DateUtils.getNowDate())/365;
                resume.setAge(age);
            }
            userinfo.setObjData(resume);
        });

        return getDataTable(list);
    }


    /**
     * 邀请投递简历
     * @param baseUserInviteApply
     * @return
     */
    @PostMapping("/addUserJobInvite")
    public AjaxResult addUserJobInvite(@RequestBody BaseUserInviteApply baseUserInviteApply)
    {
        BaseJobs job =baseJobsService.selectBaseJobsById(baseUserInviteApply.getJobId());
        if(job==null){
            return AjaxResult.error("岗位不存在");
        }
        BaseUserInviteApply apply=new BaseUserInviteApply();
        apply.setUserId(baseUserInviteApply.getUserId());
        apply.setJobId(baseUserInviteApply.getJobId());
        List<BaseUserInviteApply>  inviteList= baseUserInviteApplyService.selectBaseUserInviteApplyList(apply);
        if(inviteList.size()>0){
            return AjaxResult.error("已经邀请过该职位");
        }
        baseUserInviteApply.setJobName(job.getJobName());
        baseUserInviteApply.setInviteTime(DateUtils.getNowDate());
        baseUserInviteApply.setInviteStatus("01");
        baseUserInviteApply.setInviteUserId(SecurityUtils.getLoginUser().getUserId());
        return toAjax(baseUserInviteApplyService.insertBaseUserInviteApply(baseUserInviteApply));
    }


    @GetMapping("/getApplyJobUserslist")
    public TableDataInfo getApplyJobUserslist(BaseUserJobApply jobApply)
    {
        SysUser currentUser=SecurityUtils.getLoginUser().getUser();
        if(currentUser.getCurrentCompanyid()==null){
            return getDataTable(new ArrayList<>());
        }
        jobApply.setCompanyId(currentUser.getCurrentCompanyid());
        startPage();
        List<BaseUserJobApply> list = baseUserJobApplyService.selectCompanyUserJobApplyList(jobApply);
        list.stream().forEach(userinfo->{

            BaseUserResume resume= baseResumeService.selectBaseUserResumeDetail(userinfo.getResumeId());
            userinfo.setObjData(resume);
        });
        return getDataTable(list);
    }

    @GetMapping("/getApplyJobUsersCount")
    public AjaxResult getApplyJobUsersCount(BaseUserJobApply jobApply)
    {
        SysUser currentUser=SecurityUtils.getLoginUser().getUser();
        if(currentUser.getCurrentCompanyid()==null){
            return AjaxResult.success(new ArrayList<>());
        }
        jobApply.setCompanyId(currentUser.getCurrentCompanyid());
        List<BaseUserJobApply> list = baseUserJobApplyService.selectCompanyUserJobApplyList(jobApply);
        List<BaseUserJobApply> newNum=list.stream().filter(user->"01".equals(user.getApplyStatus())).collect(Collectors.toList());
        List<BaseUserJobApply> contact=list.stream().filter(user->"02".equals(user.getApplyStatus())).collect(Collectors.toList());
        List<BaseUserJobApply> interview=list.stream().filter(user->"04".equals(user.getApplyStatus())).collect(Collectors.toList());
        List<BaseUserJobApply> nomatch=list.stream().filter(user->"03".equals(user.getApplyStatus())).collect(Collectors.toList());
        List<BaseUserJobApply> pass=list.stream().filter(user->"05".equals(user.getApplyStatus())).collect(Collectors.toList());
        Map<String,Integer> data=new HashMap<String,Integer>();
        data.put("totalNum",list.size());
        data.put("newNum",newNum.size());
        data.put("contactNum",contact.size());
        data.put("interviewNum",interview.size());
        data.put("nomatchNum",nomatch.size());
        data.put("passNum",pass.size());
        return AjaxResult.success(data);
    }

    @GetMapping("/getUserResumeDetail")
    public AjaxResult getUserResumeDetail(@RequestParam(value="id",required = true) Long id)
    {
        BaseUserJobApply apply=baseUserJobApplyService.selectBaseUserJobApplyById(id);
        if(apply==null){
            return AjaxResult.error("申请记录不存在");
        }
        String label=DictUtils.getDictLabel("base_job_apply_status",apply.getApplyStatus());
        apply.setApplyStatusLabel(label);
        BaseUserResume resume=  baseResumeService.selectBaseUserResumeDetail(apply.getResumeId());
        AjaxResult result= AjaxResult.success(resume);
        result.put("applyData",apply);
        BaseUserJobApplyLogs applyParam=new BaseUserJobApplyLogs();
        applyParam.setApplyId(apply.getId());
        List<BaseUserJobApplyLogs>  logsList=baseUserJobApplyLogsService.selectBaseUserJobApplyLogsList(applyParam);
        result.put("logsData",logsList);
        return result;
    }

    @GetMapping("/getUserResumeByResumeId")
    public AjaxResult getUserResumeByResumeId(@RequestParam(value="id",required = true) Long id)
    {
        BaseUserResume resume=  baseResumeService.selectBaseUserResumeDetail(id);
        AjaxResult result= AjaxResult.success(resume);
        return result;
    }

    @PostMapping("/approveJobApply")
    public AjaxResult approveJobApply(@RequestBody BaseUserJobApply baseUserJobApply)
    {
        BaseUserJobApply apply=baseUserJobApplyService.selectBaseUserJobApplyById(baseUserJobApply.getId());
        if(apply==null){
            return AjaxResult.error("申请记录不存在");
        }
        if("01".equals(apply.getApplyStatus())){
            if(!"02".equals(baseUserJobApply.getApproveStatus()) && !"03".equals(baseUserJobApply.getApproveStatus()) && !"04".equals(baseUserJobApply.getApproveStatus())){
                return AjaxResult.error("状态错误");
            }
        }
        else if("02".equals(apply.getApplyStatus())){
            if(!"03".equals(baseUserJobApply.getApproveStatus()) && !"04".equals(baseUserJobApply.getApproveStatus()) && !"05".equals(baseUserJobApply.getApproveStatus())){
                return AjaxResult.error("状态错误");
            }
        }
        else if("04".equals(apply.getApplyStatus())){
            if(!"03".equals(baseUserJobApply.getApproveStatus()) && !"05".equals(baseUserJobApply.getApproveStatus()) && !"06".equals(baseUserJobApply.getApproveStatus())){
                return AjaxResult.error("状态错误");
            }
        }else{
            return AjaxResult.error("申请记录状态有误，请联系管理员");
        }
        return toAjax(baseUserJobApplyService.approveUserJobApply(baseUserJobApply));
    }

    @GetMapping("/queryJobTypeData")
    public AjaxResult queryJobTypeData()
    {
        List<BaseJobCategory> firstType=baseJobCategoryService.selectBaseJobCategoryList(new BaseJobCategory());
        List<BaseJobType> secondType=baseJobTypeService.selectJobTypeListByCategroy(new BaseJobType());
        firstType.stream().forEach(type->{
            List<BaseJobType> secondList= secondType.stream().filter(t->t.getCategoryId().intValue()==type.getCategoryId().intValue()).collect(Collectors.toList());
            type.setChildList(secondList);
        });
        return AjaxResult.success(firstType);
    }

    @GetMapping("/getCompanyAddressList")
    public AjaxResult getCompanyAddressList()
    {
        SysUser currentUser=SecurityUtils.getLoginUser().getUser();
        if(currentUser.getCurrentCompanyid()==null){
            return AjaxResult.success(new ArrayList<>());
        }
        BaseCompanyAddress param=new BaseCompanyAddress();
        param.setCompanyId(currentUser.getCurrentCompanyid());
        List<BaseCompanyAddress> addressList = companyAddressService.selectBaseCompanyAddressList(param);
        return AjaxResult.success(addressList);
    }

    @Log(title = "新增岗位", businessType = BusinessType.INSERT)
    @PostMapping("/addCompanyJob")
    public AjaxResult addCompanyJob(@RequestBody BaseJobs baseJobs)
    {
        SysUser currentUser=SecurityUtils.getLoginUser().getUser();
        if(currentUser.getCurrentCompanyid()==null){
            return AjaxResult.error("当前用户没有分配公司");
        }
        BaseCompany company= baseCompanyService.selectBaseCompanyById(currentUser.getCurrentCompanyid());
        baseJobs.setCompanyId(company.getId());
        baseJobs.setCompanyName(company.getCompanyName());
        baseJobs.setCreateUserId(currentUser.getUserId());
        baseJobs.setCreateBy(currentUser.getUserName());
        baseJobs.setStatus("01");
        BaseCompanyAddress address= companyAddressService.selectBaseCompanyAddressById(baseJobs.getAddrId());
        if(address!=null){
            String cityName=address.getCity()+address.getArea();
            baseJobs.setCityName(cityName);
        }
        return toAjax(baseJobsService.insertBaseJobs(baseJobs));
    }

    /**
     * 修改岗位
     */
    @Log(title = "岗位", businessType = BusinessType.UPDATE)
    @PutMapping("/editCompanyJob")
    public AjaxResult editCompanyJob(@RequestBody BaseJobs baseJobs)
    {
        BaseCompanyAddress address= companyAddressService.selectBaseCompanyAddressById(baseJobs.getAddrId());
        if(address!=null){
            String cityName=address.getCity()+address.getArea();
            baseJobs.setCityName(cityName);
        }
        return toAjax(baseJobsService.updateBaseJobs(baseJobs));
    }

    @Log(title = "审核岗位", businessType = BusinessType.UPDATE)
    @PutMapping("/approveCompanyJob")
    public AjaxResult approveCompanyJob(@RequestBody BaseJobs baseJobs)
    {

        BaseJobs job=baseJobsService.selectBaseJobsById(baseJobs.getId());
        if(job==null){
            return AjaxResult.error("职位不存在");
        }
        if(!"01".equals(job.getStatus())){
            return AjaxResult.error("只有待审的岗位才能进行该操作");
        }
        return toAjax(baseJobsService.approveBaseJobs(baseJobs));
    }

    @Log(title = "刷新职位", businessType = BusinessType.UPDATE)
    @GetMapping("/refreshCompanyJobData")
    public AjaxResult refreshCompanyJobData()
    {
        SysUser currentUser=SecurityUtils.getLoginUser().getUser();
        if(currentUser.getCurrentCompanyid()==null){
            return AjaxResult.error("当前用户没有分配公司");
        }
        baseJobsService.refreshBaseJobs(currentUser.getCurrentCompanyid());

        BaseJobs param=new BaseJobs();
        param.setCompanyId(currentUser.getCurrentCompanyid());
        List<BaseJobs> jobList= baseJobsService.selectBaseJobsList(param);
        jobList.stream().forEach(baseJobs->{
            BaseJobLogs log=new BaseJobLogs();
            log.setJobId(baseJobs.getId());
            log.setContent("刷新职位");
            log.setCreateTime(DateUtils.getNowDate());
            log.setCreateBy(SecurityUtils.getUsername());
            log.setRemark("");
            log.setCreateAvatar(SecurityUtils.getLoginUser().getUser().getAvatar());
            baseJobLogsService.insertBaseJobLogs(log);
        });

        return AjaxResult.success("操作成功");
    }

    @GetMapping("/getCurrentCompanyDetail")
    public AjaxResult getCurrentCompanyDetail()
    {
        SysUser currentUser=SecurityUtils.getLoginUser().getUser();
        if(currentUser.getCurrentCompanyid()==null){
            return AjaxResult.error("未分配公司，请联系管理员");
        }
        BaseCompany company= baseCompanyService.selectBaseCompanyById(currentUser.getCurrentCompanyid());
        if(company==null){
            return AjaxResult.error("未分配公司，请联系管理员");
        }
        BaseCompanyPhoto param=new BaseCompanyPhoto();
        param.setCompanyId(currentUser.getCurrentCompanyid());
        List<BaseCompanyPhoto> photoList=baseCompanyPhotoService.selectBaseCompanyPhotoList(param);
        String companyPhotos="";
        for(BaseCompanyPhoto p:photoList){
            companyPhotos+=","+p.getFileUrl();
        }
        if(StringUtils.isNotEmpty(companyPhotos)){
            companyPhotos=companyPhotos.substring(1);
        }
        company.setCompanyPhotos(companyPhotos);
        company.setPhotoList(photoList);
        return AjaxResult.success(company);
    }

    @GetMapping("/getCompanyDetail")
    public AjaxResult getCompanyDetail(@RequestParam(value = "id", required = true) Long id)
    {
        BaseCompany company= baseCompanyService.selectBaseCompanyById(id);
        if(company==null){
            return AjaxResult.error("未分配公司，请联系管理员");
        }
        BaseCompanyPhoto param=new BaseCompanyPhoto();
        param.setCompanyId(company.getId());
        List<BaseCompanyPhoto> photoList=baseCompanyPhotoService.selectBaseCompanyPhotoList(param);
        company.setPhotoList(photoList);
        return AjaxResult.success(company);
    }

    @GetMapping("/getCompanyAccountList")
    public TableDataInfo getCompanyAccountList(BaseCompanyAccountReal baseCompanyAccountReal)
    {
        SysUser currentUser=SecurityUtils.getLoginUser().getUser();
        if(currentUser.getCurrentCompanyid()==null){
            return getDataTable(new ArrayList<>());
        }
        baseCompanyAccountReal.setCompanyId(currentUser.getCurrentCompanyid());
        startPage();
        List<BaseCompanyAccountReal> list = baseCompanyAccountRealService.selectBaseCompanyAccountRealList(baseCompanyAccountReal);
        return getDataTable(list);
    }

    @Log(title = "审核公司", businessType = BusinessType.UPDATE)
    @PutMapping("/approveCompany")
    public AjaxResult approveCompany(@RequestBody BaseCompany baseCompany)
    {
        BaseCompany company=baseCompanyService.selectBaseCompanyById(baseCompany.getId());
        if(company==null){
            return AjaxResult.error("公司不存在");
        }
        if(!"01".equals(company.getAuditStatus())){
            return AjaxResult.error("只有待审的公司才能进行该操作");
        }
        return toAjax(baseCompanyService.approveBaseCompany(baseCompany));
    }

    @Log(title = "编辑公司", businessType = BusinessType.UPDATE)
    @PutMapping("/editCompanyInfo")
    public AjaxResult editCompanyInfo(@RequestBody BaseCompany baseCompany)
    {
        BaseCompany company=baseCompanyService.selectBaseCompanyById(baseCompany.getId());
        if(company==null){
            return AjaxResult.error("公司不存在");
        }
        return toAjax(baseCompanyService.updateBaseCompany(baseCompany));
    }

    @GetMapping("/getAllProvinceData")
    public AjaxResult getAllProvinceData(BaseRegionProvince baseRegionProvince)
    {
        List<BaseRegionProvince> list = baseRegionProvinceService.selectBaseRegionProvinceData(baseRegionProvince);
        return AjaxResult.success(list);
    }

    @GetMapping("/getSearchHistory")
    public AjaxResult getSearchHistory()
    {
        List<BaseSearchHistory> hotList= baseSearchHistoryService.selectHotSearchHistoryData();
        return AjaxResult.success(hotList);
    }

}
